#include "../include/train_io.h"

int send_train(int netfd, const train_t *ptrain) {
    int ret;

    // 1. 发送 cmdstat
    ret = send(netfd, &ptrain->cmdstat, sizeof(cmdstat_t), MSG_NOSIGNAL);
    if (ret != sizeof(cmdstat_t)) {
        perror("send cmdstat");
        return -1;
    }

    // 2. 发送 length
    ret = send(netfd, &ptrain->length, sizeof(int), MSG_NOSIGNAL);
    if (ret != sizeof(int)) {
        perror("send length");
        return -1;
    }

    // 3. 发送 data
    int total = 0;
    while (total < ptrain->length) {
        ret = send(netfd, ptrain->data + total, ptrain->length - total, MSG_NOSIGNAL);
        if (ret <= 0) {
            perror("send data");
            return -1;
        }
        total += ret;
    }

    return 0;
}


int recv_train(int netfd, train_t *ptrain) {
    int ret;

    // 1. 接收 cmdstat
    ret = recv(netfd, &ptrain->cmdstat, sizeof(cmdstat_t), MSG_WAITALL);
    if (ret <= 0) {
        perror("recv cmdstat");
        return -1;
    }

    // 2. 接收 length
    ret = recv(netfd, &ptrain->length, sizeof(int), MSG_WAITALL);
    if (ret <= 0) {
        perror("recv length");
        return -1;
    }

    if (ptrain->length > sizeof(ptrain->data)) {
        fprintf(stderr, "数据长度过大: %d\n", ptrain->length);
        return -1;
    }

    // 3. 接收 data
    ret = recv(netfd, ptrain->data, ptrain->length, MSG_WAITALL);
    if (ret <= 0) {
        perror("recv data");
        return -1;
    }

    return 0;
}
